package com.ww.learn.uses

import java.sql.DriverManager
import java.sql.ResultSet

class DatabaseManager(private val connectionString: String) {
    fun <T> executeQuery(sql: String, block: (ResultSet) -> T): T {
        return DriverManager.getConnection(connectionString).use { connection ->
            connection.prepareStatement(sql).use { statement ->
                statement.executeQuery().use { resultSet ->
                    block(resultSet)
                }
            }
        }
    }

    fun executeUpdate(sql: String, vararg params: Any): Int {
        return DriverManager.getConnection(connectionString).use { connection ->
            connection.prepareStatement(sql).use { statement ->
                params.forEachIndexed { index, param ->
                    statement.setObject(index + 1, param)
                }
                statement.executeUpdate()
            }
        }
    }
}

fun main() {
    val dbManager = DatabaseManager("jdbc:sqlite:sample.db")

    // 执行查询
    val userCount = dbManager.executeQuery("SELECT COUNT(*) FROM users") { resultSet ->
        if (resultSet.next()) resultSet.getInt(1) else 0
    }

    // 执行更新
    val affectedRows = dbManager.executeUpdate(
        "INSERT INTO users (name, email) VALUES (?, ?)",
        "John Doe", "john@example.com"
    )
}